package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.admin.AdminConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Resource
    ApUserMapper apUserMapper;
    @Autowired
    WemediaFeign wemediaFeign;
    @Autowired
    ArticleFeign articleFeign;

    @Override
    public ResponseResult loadListByStatus(AuthDTO dto) {
        // 1 参数检查
        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //条件查询
        Page<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApUserRealname> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        IPage<ApUserRealname> resultPage = page(page, lambdaQueryWrapper);
        //返回结果
        return new PageResponseResult(dto.getPage(), dto.getSize(), resultPage.getTotal(), resultPage.getRecords());

    }

//    @Transactional
    @GlobalTransactional(timeoutMills = 100000,rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        //参数校验
        if (dto.getId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID, "实名认证id不存在");
        }
        //根据id查询ap_user_realname
        ApUserRealname realnameInfo = this.getById(dto.getId());
        if (realnameInfo == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID, "实名认证信息不存在");
        }
        if (!AdminConstants.WAIT_AUTH.equals(realnameInfo.getStatus())) {//如果不等于1说明不是待审核状态
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_ALLOW, "实名认证信息不是待审核状态");
        }
        //根据ap_user_realname中关联的userId查询ap_user
        ApUser apUser = apUserMapper.selectById(realnameInfo.getUserId());
        if (apUser == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID, "该实名认证所关联的app账户不存在");
        }
//        this.updateById(realnameInfo);//修改实名认证状态
        //修改ap_user_realname表中status状态
        realnameInfo.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())) {
            realnameInfo.setReason(dto.getMsg());
        }
        this.updateById(realnameInfo);//修改实名认证状态

        //如果状态为9
        if (AdminConstants.PASS_AUTH.equals(status)) {
            //开通自媒体账户信息
            WmUser wmUser = this.createWmUser(apUser);
            //创建作者信息
            this.createAuthor(apUser, wmUser);
        }
//        System.out.println(1/0);
        return ResponseResult.okResult();
    }

    /**
     * @param apUser
     * @param wmUser
     */
    private void createAuthor(ApUser apUser, WmUser wmUser) {
        //查询作者信息是否已经存在
        ResponseResult<ApAuthor> result = articleFeign.findByUserId(apUser.getId());
        Integer code = result.getCode();//状态码：0
        if (code != 0) {
            throw new CustomException(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用失败");
        }
        ApAuthor apAuthor = result.getData();

        if (apAuthor != null) {
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST, "数据已经存在");
        }
        apAuthor = new ApAuthor();
        apAuthor.setName(apUser.getName());
        apAuthor.setType(2);//平台自媒体人
        apAuthor.setUserId(apUser.getId());
        apAuthor.setCreatedTime(new Date());
        apAuthor.setWmUserId(wmUser.getId());
        ResponseResult responseResult = articleFeign.save(apAuthor);
        if (responseResult.getCode().intValue() != 0) {
            throw new CustomException(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用失败");
        }

    }

    private WmUser createWmUser(ApUser apUser) {
        //根据用户名 查询wmUser是否已经创建
        ResponseResult<WmUser> result = wemediaFeign.findByName(apUser.getName());
        Integer code = result.getCode();//状态码：0
        if (code != 0) {
            throw new CustomException(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用失败");
        }
        WmUser wmUser = result.getData();
        if (wmUser != null) {
            //如果已经创建，抛出已存在异常
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST, "数据已经存在");
        }
        //创建wmUser信息 保存
        wmUser = new WmUser();
        wmUser.setApUserId(apUser.getId());
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setNickname(apUser.getName());
        wmUser.setImage(apUser.getImage());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(9);
        wmUser.setType(0);
        wmUser.setCreatedTime(new Date());
        ResponseResult<WmUser> responseResult = wemediaFeign.save(wmUser);
        if (responseResult.getCode().intValue() != 0) {//说明远程调用失败
            throw new CustomException(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用失败");
        }
        //返回保存成功的自媒体账户信息
        return responseResult.getData();
    }
}
